# MainWindow.py
# This file is part of CharTr
#
# Copyright (C) 2006 - Don Scorgie <Don@Scorgie.org> (labyrinth part)
# Copyright (C) 2008 - Nicolas Bigeard <nico.bigeard@gmail.com>  
# CharTr is free software; you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation; either version 2 of the License, or
# (at your option) any later version.
#
# CharTr is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with CharTr; if not, write to the Free Software
# Foundation, Inc., 51 Franklin St, Fifth Floor,
# Boston, MA  02110-1301  USA
#

import gtk
import cairo, pangocairo
import sha
import os
import tarfile
import gobject
import gettext
import gtk.glade
_ = gettext.gettext
import MMapArea
import UndoManager
import utils
from MapList import MapList
import xml.dom.minidom as dom
import PeriodicSaveThread
import ImageThought

map_number = 1

# UNDO varieties for us
UNDO_MODE = 0
UNDO_SHOW_EXTENDED = 1

class CharTrWindow (gobject.GObject):
    __gsignals__ = dict (title_changed      = (gobject.SIGNAL_RUN_FIRST,
                                               gobject.TYPE_NONE,
                                               (gobject.TYPE_STRING, gobject.TYPE_OBJECT)),
                         open_linked_map     = (gobject.SIGNAL_RUN_FIRST,
                                               gobject.TYPE_NONE,
                                               (gobject.TYPE_STRING, )), 
                         launch_option     = (gobject.SIGNAL_RUN_FIRST,
                                               gobject.TYPE_NONE,
                                               (gobject.TYPE_STRING, )), 
                         doc_save           = (gobject.SIGNAL_RUN_FIRST,
                                               gobject.TYPE_NONE,
                                               (gobject.TYPE_STRING, gobject.TYPE_OBJECT)),
                         file_saved         = (gobject.SIGNAL_RUN_FIRST,
                                               gobject.TYPE_NONE,
                                               (gobject.TYPE_STRING, gobject.TYPE_OBJECT)),
                         window_closed      = (gobject.SIGNAL_RUN_FIRST,
                                               gobject.TYPE_NONE,
                                               (gobject.TYPE_OBJECT, )),
                        quit      = (gobject.SIGNAL_RUN_FIRST,
                                               gobject.TYPE_NONE,
                                               (gobject.TYPE_OBJECT, )))


    def __init__ (self, filename, imported=False):
        super(CharTrWindow, self).__init__()
        # First, construct the MainArea and connect it all up
        self.undo = UndoManager.UndoManager (self)
        self.undo.block ()
        self.MainArea = MMapArea.MMapArea (self.undo)
        self.MainArea.connect ("title_changed", self.title_changed_cb)
        self.MainArea.connect ("doc_save", self.doc_save_cb)
        self.MainArea.connect ("doc_delete", self.doc_del_cb)
        self.MainArea.connect ("button-press-event", self.main_area_focus_cb)
        self.MainArea.connect ("change_buffer", self.switch_buffer_cb)
        self.MainArea.connect ("open_linked_map",self.open_linked_map_cb)
        self.MainArea.connect ("launch_option",self.launch_option_cb)
        self.MainArea.connect("quit",self.quitting_cb)
        if os.name != 'nt':
            self.MainArea.connect ("text_selection_changed", self.selection_changed_cb)
        self.MainArea.connect ("set_focus", self.main_area_focus_cb)

        #self.glade=gtk.glade.XML(utils.get_data_file_name('chartr_main.glade'))
        try: 
            self.glade=gtk.glade.XML(utils.get_data_file_name('./ui/chartr_main.glade'))
        except:
            self.glade=gtk.glade.XML(utils.get_data_file_name('../data/chartr_main.glade'))

        self.main_window = self.glade.get_widget ('window1')

        if os.name != 'nt':
            #self.main_window.set_icon_from_file(utils.get_data_file_name('chartr_icon.svg'))
            try:
                self.main_window.set_icon_name('chartr')
            except:
                self.main_window.set_icon_from_file(utils.get_data_file_name('chartr.svg'))
        else:
            #self.main_window.set_icon_from_file('chartr_icon64x64.png')
            self.main_window.set_icon_from_file('chartr.png')

        self.main_window.set_focus_child (self.MainArea)

        if gtk.gtk_version[1] > 8:
        # FIXME:  This can go when we move entirely to gtk 2.10
        # pygtk 2.8 doesn't have the correct function :(
            self.set_val = True
        else:
            self.set_val = False


        self.viewport = self.glade.get_widget('viewport1')
        self.toolbar  = self.glade.get_widget('toolbar1') 
        self.save_button = self.glade.get_widget('save')
        self.save_button.connect ('clicked', self.on_save_clicked)

        self.export_button = self.glade.get_widget('export')
        self.export_button.connect('clicked',self.export_cb)
        self.zoomin_button = self.glade.get_widget('zoomin')
        self.zoomin_button.connect('clicked',self.on_zoomin_clicked)

        self.zoomout_button = self.glade.get_widget('zoomout')
        self.zoomout_button.connect('clicked',self.on_zoomout_clicked)
        
        self.image_button = self.glade.get_widget('Image')
        self.image_button.connect('clicked',self.on_image_clicked)

        self.audio_button = self.glade.get_widget('Audio')
        self.audio_button.connect('clicked',self.on_audio_clicked)

        self.note_button = self.glade.get_widget('Note')
        self.note_button.connect('clicked',self.on_note_clicked)

        self.icon_box_button = self.glade.get_widget('Icon')
        self.icon_box_button.connect('clicked',self.on_iconbox_clicked)

        self.help_button = self.glade.get_widget('Help')
        self.help_button.connect('clicked',self.on_help_clicked)

        self.color_button = self.glade.get_widget('Color')
        self.color_button.connect('color-set',self.foreground_change_color)

        self.back_button = self.glade.get_widget('Back')
        self.back_button.connect('color-set',self.background_change_color)
        # Add in the extended info view
        self.extended = gtk.TextView ()
        self.extended.set_wrap_mode (gtk.WRAP_WORD_CHAR)
        self.invisible_buffer = gtk.TextBuffer ()

        # Connect all our signals
        self.main_window.connect ("configure_event", self.configure_cb)
        self.main_window.connect ("window-state-event", self.window_state_cb)
        self.main_window.connect ("destroy", self.close_window_cb)

        #self.glade2=gtk.glade.XML(utils.get_data_file_name('chartr_help.glade'))
        try:
            self.glade2=gtk.glade.XML(utils.get_data_file_name('./ui/chartr_help.glade'))
        except:
            self.glade2=gtk.glade.XML(utils.get_data_file_name('../data/chartr_help.glade'))

        self.help_window = self.glade2.get_widget ('helpwindow')
        self.help_window.connect("destroy",self.on_help_destroyed)

        #self.glade3=gtk.glade.XML(utils.get_data_file_name('chartr_icon_box.glade'))
        try:
            self.glade3=gtk.glade.XML(utils.get_data_file_name('./ui/chartr_icon_box.glade'))
        except:
            self.glade3=gtk.glade.XML(utils.get_data_file_name('../data/chartr_icon_box.glade'))

        self.icon_box = self.glade3.get_widget('iconbox')
        self.icon_box.connect("destroy",self.on_icon_box_destroyed)

        self.show_toolbar = True
        self.button1 = self.glade3.get_widget('button1')
        self.button2 = self.glade3.get_widget('button2')
        self.button3 = self.glade3.get_widget('button3')
        self.button4 = self.glade3.get_widget('button4')
        self.button5 = self.glade3.get_widget('button5')
        self.button6 = self.glade3.get_widget('button6')
        self.button7 = self.glade3.get_widget('button7')
        self.button8 = self.glade3.get_widget('button8')
        self.button9 = self.glade3.get_widget('button9')
        self.button10= self.glade3.get_widget('button10')
        self.button11= self.glade3.get_widget('button11')
        self.button12= self.glade3.get_widget('button12')
        self.button13= self.glade3.get_widget('button13')
        self.button14= self.glade3.get_widget('button14')
        self.button15= self.glade3.get_widget('button15')
        self.button16= self.glade3.get_widget('button16')
        self.button17= self.glade3.get_widget('button17')
        self.button18= self.glade3.get_widget('button18')
        self.button19= self.glade3.get_widget('button19')
        self.button20= self.glade3.get_widget('button20')
        self.button21= self.glade3.get_widget('button21')
        self.button22= self.glade3.get_widget('button22')
        self.button23= self.glade3.get_widget('button23')
        self.button24= self.glade3.get_widget('button24')
        self.button25= self.glade3.get_widget('button25')
        self.button26= self.glade3.get_widget('button26')
        self.button27= self.glade3.get_widget('button27')
        self.button28= self.glade3.get_widget('button28')
        self.button29= self.glade3.get_widget('button29')
        self.button30= self.glade3.get_widget('button30')
        self.button31= self.glade3.get_widget('button31')
        self.button32= self.glade3.get_widget('button32')
        self.button33= self.glade3.get_widget('button33')
        self.button34= self.glade3.get_widget('button34')
        self.button35= self.glade3.get_widget('button35')
        self.button36= self.glade3.get_widget('button36')
        self.button37= self.glade3.get_widget('button37')
        self.button38= self.glade3.get_widget('button38')
        self.button39= self.glade3.get_widget('button39')
        self.button40= self.glade3.get_widget('button40')
        self.button41= self.glade3.get_widget('button41')
        self.button42= self.glade3.get_widget('button42')
        self.button43= self.glade3.get_widget('button43')
        self.button44= self.glade3.get_widget('button44')
        self.button45= self.glade3.get_widget('button45')
        self.button46= self.glade3.get_widget('button46')
        self.button47= self.glade3.get_widget('button47')
        self.button48= self.glade3.get_widget('button48')
        self.button49= self.glade3.get_widget('button49')
        self.button50= self.glade3.get_widget('button50')
        self.button51= self.glade3.get_widget('button51')
        self.button52= self.glade3.get_widget('button52')
        self.button53= self.glade3.get_widget('button53')
        self.button54= self.glade3.get_widget('button54')
        self.button55= self.glade3.get_widget('button55')
        self.button56= self.glade3.get_widget('button56')

        self.button1.connect("clicked",self.on_button1_clicked)
        self.button2.connect("clicked",self.on_button2_clicked)
        self.button3.connect("clicked",self.on_button3_clicked)
        self.button4.connect("clicked",self.on_button4_clicked)
        self.button5.connect("clicked",self.on_button5_clicked)
        self.button6.connect("clicked",self.on_button6_clicked)
        self.button7.connect("clicked",self.on_button7_clicked)
        self.button8.connect("clicked",self.on_button8_clicked)
        self.button9.connect("clicked",self.on_button9_clicked)
        self.button10.connect("clicked",self.on_button10_clicked)
        self.button11.connect("clicked",self.on_button11_clicked)
        self.button12.connect("clicked",self.on_button12_clicked)
        self.button13.connect("clicked",self.on_button13_clicked)
        self.button14.connect("clicked",self.on_button14_clicked)
        self.button15.connect("clicked",self.on_button15_clicked)
        self.button16.connect("clicked",self.on_button16_clicked)
        self.button17.connect("clicked",self.on_button17_clicked)
        self.button18.connect("clicked",self.on_button18_clicked)
        self.button19.connect("clicked",self.on_button19_clicked)
        self.button20.connect("clicked",self.on_button20_clicked)
        self.button21.connect("clicked",self.on_button21_clicked)
        self.button22.connect("clicked",self.on_button22_clicked)
        self.button23.connect("clicked",self.on_button23_clicked)
        self.button24.connect("clicked",self.on_button24_clicked)
        self.button25.connect("clicked",self.on_button25_clicked)
        self.button26.connect("clicked",self.on_button26_clicked)
        self.button27.connect("clicked",self.on_button27_clicked)
        self.button28.connect("clicked",self.on_button28_clicked)
        self.button29.connect("clicked",self.on_button29_clicked)
        self.button30.connect("clicked",self.on_button30_clicked)
        self.button31.connect("clicked",self.on_button31_clicked)
        self.button32.connect("clicked",self.on_button32_clicked)
        self.button33.connect("clicked",self.on_button33_clicked)
        self.button34.connect("clicked",self.on_button34_clicked)
        self.button35.connect("clicked",self.on_button35_clicked)
        self.button36.connect("clicked",self.on_button36_clicked)
        self.button37.connect("clicked",self.on_button37_clicked)
        self.button38.connect("clicked",self.on_button38_clicked)
        self.button39.connect("clicked",self.on_button39_clicked)
        self.button40.connect("clicked",self.on_button40_clicked)
        self.button41.connect("clicked",self.on_button41_clicked)
        self.button42.connect("clicked",self.on_button42_clicked)
        self.button43.connect("clicked",self.on_button43_clicked)
        self.button44.connect("clicked",self.on_button44_clicked)
        self.button45.connect("clicked",self.on_button45_clicked)
        self.button46.connect("clicked",self.on_button46_clicked)
        self.button47.connect("clicked",self.on_button47_clicked)
        self.button48.connect("clicked",self.on_button48_clicked)
        self.button49.connect("clicked",self.on_button49_clicked)
        self.button50.connect("clicked",self.on_button50_clicked)
        self.button51.connect("clicked",self.on_button51_clicked)
        self.button52.connect("clicked",self.on_button52_clicked)
        self.button53.connect("clicked",self.on_button53_clicked)
        self.button54.connect("clicked",self.on_button54_clicked)
        self.button55.connect("clicked",self.on_button55_clicked)
        self.button56.connect("clicked",self.on_button56_clicked)

        self.MainArea.set_size_request(600,500)
        # Deal with loading the map
        if not filename:
            self.MainArea.set_size_request (600, 500)
            self.map_number = MapList.count() +1
            # TODO: This shouldn't be set to a hard-coded number.  Fix.
            self.pane_pos = 500
            self.title_cp = _("Untitled Map %d" % self.map_number)
            self.map_number += 1
            self.mode = MMapArea.MODE_EDITING
            self.extended_visible = False
        else:
            self.parse_file (filename)

        self.start_timer()
       # Other stuff
        self.width, self.height = self.main_window.get_size ()

        self.viewport.add(self.MainArea)
        self.main_window.show_all()        
        # if we import, we dump the old filename to create a new hashed one
        if imported:
            self.save_file = None
        else:
            self.save_file = filename
            
        self.maximised = False
        self.view_type = 0
        self.main_window.set_title (self.title_cp)
        self.show_help_window = False
        self.show_icon_box = False
        self.help_destroyed = False
        self.icon_box_destroyed = False
        #if self.set_val:
        #    self.act.set_current_value (self.mode)
        #self.ext_act.set_active (self.extended_visible)

    def quitting_cb(self,arg1,arg2):
        self.main_window.emit("destroy")

    def on_button1_clicked(self,widget):
        coords = self.MainArea.get_selected_thought_coords()
        if coords[0]!=0 or coords[1]!=0:
            thought = self.MainArea.create_new_thought(coords,6,1)
            
            lnk = self.MainArea.create_link (self.MainArea.selected[0], None, thought)
            thought.link = lnk
            self.MainArea.invalidate()


    def on_button2_clicked(self,widget):
        coords = self.MainArea.get_selected_thought_coords()
        if coords[0]!=0 or coords[1]!=0:
            thought = self.MainArea.create_new_thought(coords,6,2)
            
            lnk = self.MainArea.create_link (self.MainArea.selected[0], None, thought)
            thought.link = lnk
            self.MainArea.invalidate()


    def on_button3_clicked(self,widget):
        coords = self.MainArea.get_selected_thought_coords()
        if coords[0]!=0 or coords[1]!=0:
            thought = self.MainArea.create_new_thought(coords,6,3)
            
            lnk = self.MainArea.create_link (self.MainArea.selected[0], None, thought)
            thought.link = lnk
            self.MainArea.invalidate()


    def on_button4_clicked(self,widget):
        coords = self.MainArea.get_selected_thought_coords()
        if coords[0]!=0 or coords[1]!=0:
            thought = self.MainArea.create_new_thought(coords,6,4)
            
            lnk = self.MainArea.create_link (self.MainArea.selected[0], None, thought)
            thought.link = lnk
            self.MainArea.invalidate()


    def on_button5_clicked(self,widget):
        coords = self.MainArea.get_selected_thought_coords()
        if coords[0]!=0 or coords[1]!=0:
            thought = self.MainArea.create_new_thought(coords,6,5)
            
            lnk = self.MainArea.create_link (self.MainArea.selected[0], None, thought)
            thought.link = lnk
            self.MainArea.invalidate()


    def on_button6_clicked(self,widget):
        coords = self.MainArea.get_selected_thought_coords()
        if coords[0]!=0 or coords[1]!=0:
            thought = self.MainArea.create_new_thought(coords,6,6)
            
            lnk = self.MainArea.create_link (self.MainArea.selected[0], None, thought)
            thought.link = lnk
            self.MainArea.invalidate()


    def on_button7_clicked(self,widget):
        coords = self.MainArea.get_selected_thought_coords()
        if coords[0]!=0 or coords[1]!=0:
            thought = self.MainArea.create_new_thought(coords,6,7)
            
            lnk = self.MainArea.create_link (self.MainArea.selected[0], None, thought)
            thought.link = lnk
            self.MainArea.invalidate()


    def on_button8_clicked(self,widget):
        coords = self.MainArea.get_selected_thought_coords()
        if coords[0]!=0 or coords[1]!=0:
            thought = self.MainArea.create_new_thought(coords,6,8)
            
            lnk = self.MainArea.create_link (self.MainArea.selected[0], None, thought)
            thought.link = lnk
            self.MainArea.invalidate()


    def on_button9_clicked(self,widget):
        coords = self.MainArea.get_selected_thought_coords()
        if coords[0]!=0 or coords[1]!=0:
            thought = self.MainArea.create_new_thought(coords,6,9)
            
            lnk = self.MainArea.create_link (self.MainArea.selected[0], None, thought)
            thought.link = lnk
            self.MainArea.invalidate()


    def on_button10_clicked(self,widget):
        coords = self.MainArea.get_selected_thought_coords()
        if coords[0]!=0 or coords[1]!=0:
            thought = self.MainArea.create_new_thought(coords,6,10)
            
            lnk = self.MainArea.create_link (self.MainArea.selected[0], None, thought)
            thought.link = lnk
            self.MainArea.invalidate()


    def on_button11_clicked(self,widget):
        coords = self.MainArea.get_selected_thought_coords()
        if coords[0]!=0 or coords[1]!=0:
            thought = self.MainArea.create_new_thought(coords,6,11)
            
            lnk = self.MainArea.create_link (self.MainArea.selected[0], None, thought)
            thought.link = lnk
            self.MainArea.invalidate()


    def on_button12_clicked(self,widget):
        coords = self.MainArea.get_selected_thought_coords()
        if coords[0]!=0 or coords[1]!=0:
            thought = self.MainArea.create_new_thought(coords,6,12)
            
            lnk = self.MainArea.create_link (self.MainArea.selected[0], None, thought)
            thought.link = lnk
            self.MainArea.invalidate()


    def on_button13_clicked(self,widget):
        coords = self.MainArea.get_selected_thought_coords()
        if coords[0]!=0 or coords[1]!=0:
            thought = self.MainArea.create_new_thought(coords,6,13)
            
            lnk = self.MainArea.create_link (self.MainArea.selected[0], None, thought)
            thought.link = lnk
            self.MainArea.invalidate()


    def on_button14_clicked(self,widget):
        coords = self.MainArea.get_selected_thought_coords()
        if coords[0]!=0 or coords[1]!=0:
            thought = self.MainArea.create_new_thought(coords,6,14)
            
            lnk = self.MainArea.create_link (self.MainArea.selected[0], None, thought)
            thought.link = lnk
            self.MainArea.invalidate()


    def on_button15_clicked(self,widget):
        coords = self.MainArea.get_selected_thought_coords()
        if coords[0]!=0 or coords[1]!=0:
            thought = self.MainArea.create_new_thought(coords,6,15)
            
            lnk = self.MainArea.create_link (self.MainArea.selected[0], None, thought)
            thought.link = lnk
            self.MainArea.invalidate()


    def on_button16_clicked(self,widget):
        coords = self.MainArea.get_selected_thought_coords()
        if coords[0]!=0 or coords[1]!=0:
            thought = self.MainArea.create_new_thought(coords,6,16)
            
            lnk = self.MainArea.create_link (self.MainArea.selected[0], None, thought)
            thought.link = lnk
            self.MainArea.invalidate()


    def on_button17_clicked(self,widget):
        coords = self.MainArea.get_selected_thought_coords()
        if coords[0]!=0 or coords[1]!=0:
            thought = self.MainArea.create_new_thought(coords,6,17)
            
            lnk = self.MainArea.create_link (self.MainArea.selected[0], None, thought)
            thought.link = lnk
            self.MainArea.invalidate()


    def on_button18_clicked(self,widget):
        coords = self.MainArea.get_selected_thought_coords()
        if coords[0]!=0 or coords[1]!=0:
            thought = self.MainArea.create_new_thought(coords,6,18)
            
            lnk = self.MainArea.create_link (self.MainArea.selected[0], None, thought)
            thought.link = lnk
            self.MainArea.invalidate()


    def on_button19_clicked(self,widget):
        coords = self.MainArea.get_selected_thought_coords()
        if coords[0]!=0 or coords[1]!=0:
            thought = self.MainArea.create_new_thought(coords,6,19)
            
            lnk = self.MainArea.create_link (self.MainArea.selected[0], None, thought)
            thought.link = lnk
            self.MainArea.invalidate()


    def on_button20_clicked(self,widget):
        coords = self.MainArea.get_selected_thought_coords()
        if coords[0]!=0 or coords[1]!=0:
            thought = self.MainArea.create_new_thought(coords,6,20)
            
            lnk = self.MainArea.create_link (self.MainArea.selected[0], None, thought)
            thought.link = lnk
            self.MainArea.invalidate()


    def on_button21_clicked(self,widget):
        coords = self.MainArea.get_selected_thought_coords()
        if coords[0]!=0 or coords[1]!=0:
            thought = self.MainArea.create_new_thought(coords,6,21)
            
            lnk = self.MainArea.create_link (self.MainArea.selected[0], None, thought)
            thought.link = lnk
            self.MainArea.invalidate()


    def on_button22_clicked(self,widget):
        coords = self.MainArea.get_selected_thought_coords()
        if coords[0]!=0 or coords[1]!=0:
            thought = self.MainArea.create_new_thought(coords,6,22)
            
            lnk = self.MainArea.create_link (self.MainArea.selected[0], None, thought)
            thought.link = lnk
            self.MainArea.invalidate()


    def on_button23_clicked(self,widget):
        coords = self.MainArea.get_selected_thought_coords()
        if coords[0]!=0 or coords[1]!=0:
            thought = self.MainArea.create_new_thought(coords,6,23)
            
            lnk = self.MainArea.create_link (self.MainArea.selected[0], None, thought)
            thought.link = lnk
            self.MainArea.invalidate()


    def on_button24_clicked(self,widget):
        coords = self.MainArea.get_selected_thought_coords()
        if coords[0]!=0 or coords[1]!=0:
            thought = self.MainArea.create_new_thought(coords,6,24)
            
            lnk = self.MainArea.create_link (self.MainArea.selected[0], None, thought)
            thought.link = lnk
            self.MainArea.invalidate()


    def on_button25_clicked(self,widget):
        coords = self.MainArea.get_selected_thought_coords()
        if coords[0]!=0 or coords[1]!=0:
            thought = self.MainArea.create_new_thought(coords,6,25)
            
            lnk = self.MainArea.create_link (self.MainArea.selected[0], None, thought)
            thought.link = lnk
            self.MainArea.invalidate()


    def on_button26_clicked(self,widget):
        coords = self.MainArea.get_selected_thought_coords()
        if coords[0]!=0 or coords[1]!=0:
            thought = self.MainArea.create_new_thought(coords,6,26)
            
            lnk = self.MainArea.create_link (self.MainArea.selected[0], None, thought)
            thought.link = lnk
            self.MainArea.invalidate()


    def on_button27_clicked(self,widget):
        coords = self.MainArea.get_selected_thought_coords()
        if coords[0]!=0 or coords[1]!=0:
            thought = self.MainArea.create_new_thought(coords,6,27)
            
            lnk = self.MainArea.create_link (self.MainArea.selected[0], None, thought)
            thought.link = lnk
            self.MainArea.invalidate()

    def on_button28_clicked(self,widget):
        coords = self.MainArea.get_selected_thought_coords()
        if coords[0]!=0 or coords[1]!=0:
            thought = self.MainArea.create_new_thought(coords,6,28)
            
            lnk = self.MainArea.create_link (self.MainArea.selected[0], None, thought)
            thought.link = lnk
            self.MainArea.invalidate()


    def on_button29_clicked(self,widget):
        coords = self.MainArea.get_selected_thought_coords()
        if coords[0]!=0 or coords[1]!=0:
            thought = self.MainArea.create_new_thought(coords,6,29)
            
            lnk = self.MainArea.create_link (self.MainArea.selected[0], None, thought)
            thought.link = lnk
            self.MainArea.invalidate()

    def on_button30_clicked(self,widget):
        coords = self.MainArea.get_selected_thought_coords()
        if coords[0]!=0 or coords[1]!=0:
            thought = self.MainArea.create_new_thought(coords,6,30)
            
            lnk = self.MainArea.create_link (self.MainArea.selected[0], None, thought)
            thought.link = lnk
            self.MainArea.invalidate()

    def on_button31_clicked(self,widget):
        coords = self.MainArea.get_selected_thought_coords()
        if coords[0]!=0 or coords[1]!=0:
            thought = self.MainArea.create_new_thought(coords,6,31)
            
            lnk = self.MainArea.create_link (self.MainArea.selected[0], None, thought)

            thought.link = lnk
            self.MainArea.invalidate()

    def on_button32_clicked(self,widget):
        coords = self.MainArea.get_selected_thought_coords()
        if coords[0]!=0 or coords[1]!=0:
            thought = self.MainArea.create_new_thought(coords,6,32)
            
            lnk = self.MainArea.create_link (self.MainArea.selected[0], None, thought)
            thought.link = lnk
            self.MainArea.invalidate()

    def on_button33_clicked(self,widget):
        coords = self.MainArea.get_selected_thought_coords()
        if coords[0]!=0 or coords[1]!=0:
            thought = self.MainArea.create_new_thought(coords,6,33)
            
            lnk = self.MainArea.create_link (self.MainArea.selected[0], None, thought)
            thought.link = lnk
            self.MainArea.invalidate()

    def on_button34_clicked(self,widget):
        coords = self.MainArea.get_selected_thought_coords()
        if coords[0]!=0 or coords[1]!=0:
            thought = self.MainArea.create_new_thought(coords,6,34)
            
            lnk = self.MainArea.create_link (self.MainArea.selected[0], None, thought)
            thought.link = lnk
            self.MainArea.invalidate()

    def on_button35_clicked(self,widget):
        coords = self.MainArea.get_selected_thought_coords()
        if coords[0]!=0 or coords[1]!=0:
            thought = self.MainArea.create_new_thought(coords,6,35)
            
            lnk = self.MainArea.create_link (self.MainArea.selected[0], None, thought)
            thought.link = lnk
            self.MainArea.invalidate()

    def on_button36_clicked(self,widget):
        coords = self.MainArea.get_selected_thought_coords()
        if coords[0]!=0 or coords[1]!=0:
            thought = self.MainArea.create_new_thought(coords,6,36)
            
            lnk = self.MainArea.create_link (self.MainArea.selected[0], None, thought)
            thought.link = lnk
            self.MainArea.invalidate()

    def on_button37_clicked(self,widget):
        coords = self.MainArea.get_selected_thought_coords()
        if coords[0]!=0 or coords[1]!=0:
            thought = self.MainArea.create_new_thought(coords,6,37)
            
            lnk = self.MainArea.create_link (self.MainArea.selected[0], None, thought)
            thought.link = lnk
            self.MainArea.invalidate()

    def on_button38_clicked(self,widget):
        coords = self.MainArea.get_selected_thought_coords()
        if coords[0]!=0 or coords[1]!=0:
            thought = self.MainArea.create_new_thought(coords,6,38)
            
            lnk = self.MainArea.create_link (self.MainArea.selected[0], None, thought)
            thought.link = lnk
            self.MainArea.invalidate()

    def on_button39_clicked(self,widget):
        coords = self.MainArea.get_selected_thought_coords()
        if coords[0]!=0 or coords[1]!=0:
            thought = self.MainArea.create_new_thought(coords,6,39)
            
            lnk = self.MainArea.create_link (self.MainArea.selected[0], None, thought)
            thought.link = lnk
            self.MainArea.invalidate()

    def on_button40_clicked(self,widget):
        coords = self.MainArea.get_selected_thought_coords()
        if coords[0]!=0 or coords[1]!=0:
            thought = self.MainArea.create_new_thought(coords,6,40)
            
            lnk = self.MainArea.create_link (self.MainArea.selected[0], None, thought)
            thought.link = lnk
            self.MainArea.invalidate()

    def on_button41_clicked(self,widget):
        coords = self.MainArea.get_selected_thought_coords()
        if coords[0]!=0 or coords[1]!=0:
            thought = self.MainArea.create_new_thought(coords,6,41)
            
            lnk = self.MainArea.create_link (self.MainArea.selected[0], None, thought)
            thought.link = lnk
            self.MainArea.invalidate()

    def on_button42_clicked(self,widget):
        coords = self.MainArea.get_selected_thought_coords()
        if coords[0]!=0 or coords[1]!=0:
            thought = self.MainArea.create_new_thought(coords,6,42)
            
            lnk = self.MainArea.create_link (self.MainArea.selected[0], None, thought)
            thought.link = lnk
            self.MainArea.invalidate()

    def on_button43_clicked(self,widget):
        coords = self.MainArea.get_selected_thought_coords()
        if coords[0]!=0 or coords[1]!=0:
            thought = self.MainArea.create_new_thought(coords,6,43)
            
            lnk = self.MainArea.create_link (self.MainArea.selected[0], None, thought)
            thought.link = lnk
            self.MainArea.invalidate()

    def on_button44_clicked(self,widget):
        coords = self.MainArea.get_selected_thought_coords()
        if coords[0]!=0 or coords[1]!=0:
            thought = self.MainArea.create_new_thought(coords,6,44)
            
            lnk = self.MainArea.create_link (self.MainArea.selected[0], None, thought)
            thought.link = lnk
            self.MainArea.invalidate()

    def on_button45_clicked(self,widget):
        coords = self.MainArea.get_selected_thought_coords()
        if coords[0]!=0 or coords[1]!=0:
            thought = self.MainArea.create_new_thought(coords,6,45)
            
            lnk = self.MainArea.create_link (self.MainArea.selected[0], None, thought)
            thought.link = lnk
            self.MainArea.invalidate()

    def on_button46_clicked(self,widget):
        coords = self.MainArea.get_selected_thought_coords()
        if coords[0]!=0 or coords[1]!=0:
            thought = self.MainArea.create_new_thought(coords,6,46)
            
            lnk = self.MainArea.create_link (self.MainArea.selected[0], None, thought)
            thought.link = lnk
            self.MainArea.invalidate()

    def on_button47_clicked(self,widget):
        coords = self.MainArea.get_selected_thought_coords()
        if coords[0]!=0 or coords[1]!=0:
            thought = self.MainArea.create_new_thought(coords,6,47)
            
            lnk = self.MainArea.create_link (self.MainArea.selected[0], None, thought)

            thought.link = lnk
            self.MainArea.invalidate()

    def on_button48_clicked(self,widget):
        coords = self.MainArea.get_selected_thought_coords()
        if coords[0]!=0 or coords[1]!=0:
            thought = self.MainArea.create_new_thought(coords,6,48)
            
            lnk = self.MainArea.create_link (self.MainArea.selected[0], None, thought)
            thought.link = lnk
            self.MainArea.invalidate()

    def on_button49_clicked(self,widget):
        coords = self.MainArea.get_selected_thought_coords()
        if coords[0]!=0 or coords[1]!=0:
            thought = self.MainArea.create_new_thought(coords,6,49)
            
            lnk = self.MainArea.create_link (self.MainArea.selected[0], None, thought)
            thought.link = lnk
            self.MainArea.invalidate()

    def on_button50_clicked(self,widget):
        coords = self.MainArea.get_selected_thought_coords()
        if coords[0]!=0 or coords[1]!=0:
            thought = self.MainArea.create_new_thought(coords,6,50)
            lnk = self.MainArea.create_link (self.MainArea.selected[0], None, thought)
            thought.link = lnk
            self.MainArea.invalidate()


    def on_button51_clicked(self,widget):
        coords = self.MainArea.get_selected_thought_coords()
        if coords[0]!=0 or coords[1]!=0:
            thought = self.MainArea.create_new_thought(coords,6,51)
            lnk = self.MainArea.create_link (self.MainArea.selected[0], None, thought)
            thought.link = lnk
            self.MainArea.invalidate()


    def on_button52_clicked(self,widget):
        coords = self.MainArea.get_selected_thought_coords()
        if coords[0]!=0 or coords[1]!=0:
            thought = self.MainArea.create_new_thought(coords,6,52)
            lnk = self.MainArea.create_link (self.MainArea.selected[0], None, thought)
            thought.link = lnk
            self.MainArea.invalidate()


    def on_button53_clicked(self,widget):
        coords = self.MainArea.get_selected_thought_coords()
        if coords[0]!=0 or coords[1]!=0:
            thought = self.MainArea.create_new_thought(coords,6,53)
            lnk = self.MainArea.create_link (self.MainArea.selected[0], None, thought)
            thought.link = lnk
            self.MainArea.invalidate()


    def on_button54_clicked(self,widget):
        coords = self.MainArea.get_selected_thought_coords()
        if coords[0]!=0 or coords[1]!=0:
            thought = self.MainArea.create_new_thought(coords,6,54)
            lnk = self.MainArea.create_link (self.MainArea.selected[0], None, thought)
            thought.link = lnk
            self.MainArea.invalidate()


    def on_button55_clicked(self,widget):
        coords = self.MainArea.get_selected_thought_coords()
        if coords[0]!=0 or coords[1]!=0:
            thought = self.MainArea.create_new_thought(coords,6,55)
            lnk = self.MainArea.create_link (self.MainArea.selected[0], None, thought)
            thought.link = lnk
            self.MainArea.invalidate()

    def on_button56_clicked(self,widget):
        coords = self.MainArea.get_selected_thought_coords()
        if coords[0]!=0 or coords[1]!=0:
            thought = self.MainArea.create_new_thought(coords,6,56)
            lnk = self.MainArea.create_link (self.MainArea.selected[0], None, thought)
            thought.link = lnk
            self.MainArea.invalidate()



    def foreground_change_color (self, button):
        color = button.get_color()
        self.MainArea.set_foreground_color(color)

    def background_change_color (self, button):
        color = button.get_color()
        self.MainArea.set_background_color(color)

    def on_save_clicked (self,widget):
        pass

    def link_thoughts_cb (self, arg):
        self.MainArea.link_menu_cb ()

    def undo_show_extended (self, action, mode):
        self.undo.block ()
        self.ext_act.set_active (not self.ext_act.get_active ())
        self.undo.unblock ()

    def view_extend_cb (self, arg):
        self.undo.add_undo (UndoManager.UndoAction (self, UNDO_SHOW_EXTENDED, self.undo_show_extended))
        self.extended_visible = arg.get_active ()
        if self.extended_visible:
            self.swin.show ()
            self.view_type = 1
        else:
            self.swin.hide ()
            self.view_type = 0

    def on_zoomout_clicked(self,widget):
        self.MainArea.scale_fac /= 1.02 
        self.MainArea.invalidate()

    def on_zoomin_clicked(self,widget):
        self.MainArea.scale_fac *= 1.02
        self.MainArea.invalidate()

    def on_image_clicked(self,widget):
        coords = self.MainArea.get_selected_thought_coords()
        if coords[0]!=0 or coords[1]!=0:
            thought = self.MainArea.create_new_thought(coords,1)
            lnk = self.MainArea.create_link (self.MainArea.selected[0], None, thought)
            
            thought.link = lnk
            self.MainArea.invalidate()

    def on_note_clicked(self,widget):
        coords = self.MainArea.get_selected_thought_coords()
        if coords[0]!=0 or coords[1]!=0:
            thought = self.MainArea.create_new_thought(coords,3)
            lnk = self.MainArea.create_link (self.MainArea.selected[0], None, thought)
            thought.link = lnk 
            self.MainArea.invalidate()

    def on_help_destroyed(self,widget):
        self.help_destroyed = True
        self.show_help_window = False
        
    def on_icon_box_destroyed(self,widget):
        self.icon_box_destroyed = True
        self.show_icon_box = False
    
    def on_iconbox_clicked(self,widget):
        if not self.show_icon_box:
            if self.icon_box_destroyed:
                #self.glade3 = gtk.glade.XML(utils.get_data_file_name('chartr_icon_box.glade'))
                try:
                    self.glade3 = gtk.glade.XML(utils.get_data_file_name('./ui/chartr_icon_box.glade'))
                except:
                    self.glade3 = gtk.glade.XML(utils.get_data_file_name('../data/chartr_icon_box.glade'))
                self.icon_box = self.glade3.get_widget ('iconbox')
                self.icon_box.connect("destroy",self.on_icon_box_destroyed)
                self.icon_box_destroyed = False

                self.button1 = self.glade3.get_widget('button1')
                self.button2 = self.glade3.get_widget('button2')
                self.button3 = self.glade3.get_widget('button3')
                self.button4 = self.glade3.get_widget('button4')
                self.button5 = self.glade3.get_widget('button5')
                self.button6 = self.glade3.get_widget('button6')
                self.button7 = self.glade3.get_widget('button7')
                self.button8 = self.glade3.get_widget('button8')
                self.button9 = self.glade3.get_widget('button9')
                self.button10= self.glade3.get_widget('button10')
                self.button11= self.glade3.get_widget('button11')
                self.button12= self.glade3.get_widget('button12')
                self.button13= self.glade3.get_widget('button13')
                self.button14= self.glade3.get_widget('button14')
                self.button15= self.glade3.get_widget('button15')
                self.button16= self.glade3.get_widget('button16')
                self.button17= self.glade3.get_widget('button17')
                self.button18= self.glade3.get_widget('button18')
                self.button19= self.glade3.get_widget('button19')
                self.button20= self.glade3.get_widget('button20')
                self.button21= self.glade3.get_widget('button21')
                self.button22= self.glade3.get_widget('button22')
                self.button23= self.glade3.get_widget('button23')
                self.button24= self.glade3.get_widget('button24')
                self.button25= self.glade3.get_widget('button25')
                self.button26= self.glade3.get_widget('button26')
                self.button27= self.glade3.get_widget('button27')
                self.button28= self.glade3.get_widget('button28')
                self.button29= self.glade3.get_widget('button29')
                self.button30= self.glade3.get_widget('button30')
                self.button31= self.glade3.get_widget('button31')
                self.button32= self.glade3.get_widget('button32')
                self.button33= self.glade3.get_widget('button33')
                self.button34= self.glade3.get_widget('button34')
                self.button35= self.glade3.get_widget('button35')
                self.button36= self.glade3.get_widget('button36')
                self.button37= self.glade3.get_widget('button37')
                self.button38= self.glade3.get_widget('button38')
                self.button39= self.glade3.get_widget('button39')
                self.button40= self.glade3.get_widget('button40')
                self.button41= self.glade3.get_widget('button41')
                self.button42= self.glade3.get_widget('button42')
                self.button43= self.glade3.get_widget('button43')
                self.button44= self.glade3.get_widget('button44')
                self.button45= self.glade3.get_widget('button45')
                self.button46= self.glade3.get_widget('button46')
                self.button47= self.glade3.get_widget('button47')
                self.button48= self.glade3.get_widget('button48')
                self.button49= self.glade3.get_widget('button49')
                self.button50= self.glade3.get_widget('button50')
                self.button51= self.glade3.get_widget('button51')
                self.button52= self.glade3.get_widget('button52')
                self.button53= self.glade3.get_widget('button53')
                self.button54= self.glade3.get_widget('button54')
                self.button55= self.glade3.get_widget('button55')
                self.button56= self.glade3.get_widget('button56')

                self.button1.connect("clicked",self.on_button1_clicked)
                self.button2.connect("clicked",self.on_button2_clicked)
                self.button3.connect("clicked",self.on_button3_clicked)
                self.button4.connect("clicked",self.on_button4_clicked)
                self.button5.connect("clicked",self.on_button5_clicked)
                self.button6.connect("clicked",self.on_button6_clicked)
                self.button7.connect("clicked",self.on_button7_clicked)
                self.button8.connect("clicked",self.on_button8_clicked)
                self.button9.connect("clicked",self.on_button9_clicked)
                self.button10.connect("clicked",self.on_button10_clicked)
                self.button11.connect("clicked",self.on_button11_clicked)
                self.button12.connect("clicked",self.on_button12_clicked)
                self.button13.connect("clicked",self.on_button13_clicked)
                self.button14.connect("clicked",self.on_button14_clicked)
                self.button15.connect("clicked",self.on_button15_clicked)
                self.button16.connect("clicked",self.on_button16_clicked)
                self.button17.connect("clicked",self.on_button17_clicked)
                self.button18.connect("clicked",self.on_button18_clicked)
                self.button19.connect("clicked",self.on_button19_clicked)
                self.button20.connect("clicked",self.on_button20_clicked)
                self.button21.connect("clicked",self.on_button21_clicked)
                self.button22.connect("clicked",self.on_button22_clicked)
                self.button23.connect("clicked",self.on_button23_clicked)
                self.button24.connect("clicked",self.on_button24_clicked)
                self.button25.connect("clicked",self.on_button25_clicked)
                self.button26.connect("clicked",self.on_button26_clicked)
                self.button27.connect("clicked",self.on_button27_clicked)
                self.button28.connect("clicked",self.on_button28_clicked)
                self.button29.connect("clicked",self.on_button29_clicked)
                self.button30.connect("clicked",self.on_button30_clicked)
                self.button31.connect("clicked",self.on_button31_clicked)
                self.button32.connect("clicked",self.on_button32_clicked)
                self.button33.connect("clicked",self.on_button33_clicked)
                self.button34.connect("clicked",self.on_button34_clicked)
                self.button35.connect("clicked",self.on_button35_clicked)
                self.button36.connect("clicked",self.on_button36_clicked)
                self.button37.connect("clicked",self.on_button37_clicked)
                self.button38.connect("clicked",self.on_button38_clicked)
                self.button39.connect("clicked",self.on_button39_clicked)
                self.button40.connect("clicked",self.on_button40_clicked)
                self.button41.connect("clicked",self.on_button41_clicked)
                self.button42.connect("clicked",self.on_button42_clicked)
                self.button43.connect("clicked",self.on_button43_clicked)
                self.button44.connect("clicked",self.on_button44_clicked)
                self.button45.connect("clicked",self.on_button45_clicked)
                self.button46.connect("clicked",self.on_button46_clicked)
                self.button47.connect("clicked",self.on_button47_clicked)
                self.button48.connect("clicked",self.on_button48_clicked)
                self.button49.connect("clicked",self.on_button49_clicked)
                self.button50.connect("clicked",self.on_button50_clicked)
                self.button51.connect("clicked",self.on_button51_clicked)
                self.button52.connect("clicked",self.on_button52_clicked)
                self.button53.connect("clicked",self.on_button53_clicked)
                self.button54.connect("clicked",self.on_button54_clicked)
                self.button55.connect("clicked",self.on_button55_clicked)
                self.button56.connect("clicked",self.on_button56_clicked)


            self.icon_box.show()
            self.show_icon_box = True
        else:
            self.icon_box.hide()
            self.show_icon_box = False
 
    def on_help_clicked(self,widget):
        if not self.show_help_window:
            if self.help_destroyed:
                #self.glade2=gtk.glade.XML(utils.get_data_file_name('chartr_help.glade'))
                try:
                    self.glade2=gtk.glade.XML(utils.get_data_file_name('./ui/chartr_help.glade'))
                except:
                    self.glade2=gtk.glade.XML(utils.get_data_file_name('../data/chartr_help.glade'))
                self.help_window = self.glade2.get_widget ('helpwindow')
                self.help_window.connect("destroy",self.on_help_destroyed)
                self.help_destroyed = False
            self.help_window.show()
            self.show_help_window = True
        else:
            self.help_window.hide()
            self.show_help_window = False
        
    def on_audio_clicked(self,widget):
        coords = self.MainArea.get_selected_thought_coords()
        if coords[0]!=0 or coords[1]!=0:
            thought = self.MainArea.create_new_thought(coords,4)
            lnk = self.MainArea.create_link (self.MainArea.selected[0], None, thought)
            thought.link = lnk
            self.MainArea.invalidate()

    def pos_changed (self, panes, arg2):
        self.pane_pos = panes.get_position ()

    def bold_toggled (self, action):
        self.bold_state = (not self.bold_state)
        if self.bold_block:
            self.bold_block = False
            return
        if self.extended.is_focus ():
            self.extended.get_buffer().set_bold(action.get_active())
        else:
            self.MainArea.set_bold (action.get_active())

    def italic_toggled (self, action):
        self.italic_state = (not self.italic_state)
        if self.italic_block:
            self.italic_block = False
            return
        if self.extended.is_focus ():
            self.extended.get_buffer().set_italics(action.get_active())
        else:
            self.MainArea.set_italics (action.get_active())

    def underline_toggled (self, action):
        self.underline_state = (not self.underline_state)
        if self.underline_block:
            self.underline_block = False
            return
        if self.extended.is_focus ():
            self.extended.get_buffer().set_underline(action.get_active())
        else:
            self.MainArea.set_underline (action.get_active())

    def background_change_cb (self, button):
        if not self.extended.is_focus ():
            self.MainArea.set_background_color (button.get_color())

    def font_change_cb (self, button):
        if not self.extended.is_focus ():
            self.MainArea.set_font (button.get_font_name ())

    def zoomin_cb(self, arg):
        self.MainArea.scale_fac*=1.2
        self.MainArea.invalidate()
        
    def zoomout_cb(self, arg):
        self.MainArea.scale_fac/=1.2
        self.MainArea.invalidate()

    def new_window_cb (self, arg):
        global_new_window ()
        return

    def switch_buffer_cb (self, arg, new_buffer):
        if new_buffer:
            self.extended.set_editable (True)
            self.extended.set_buffer (new_buffer)
        else:
            self.extended.set_buffer (self.invisible_buffer)
            self.extended.set_editable (False)
            
    def thought_selected_cb (self, arg, background_color, foreground_color):
        if background_color:
            self.background_widget.set_color(background_color)
        if foreground_color:
            self.foreground_widget.set_color(foreground_color)
        
    def main_area_focus_cb (self, arg, event, extended = False):
        if not extended:
            self.MainArea.grab_focus ()
        else:
            self.extended.grab_focus ()

    def revert_mode (self, action, mode):
        self.undo.block ()
        if mode == UndoManager.UNDO:
            self.mode_request_cb (None, action.args[0])
        else:
            self.mode_request_cb (None, action.args[1])
        self.undo.unblock ()

    def mode_change_cb (self, base, activated):
        self.MainArea.set_mode (activated.get_current_value ())
        self.mode = activated.get_current_value ()
        return

    def mode_request_cb (self, widget, mode):
        if self.set_val:
            self.act.set_current_value (mode)
        else:
            pass

    def open_linked_map_cb(self,widget,new_title):
        self.emit("open_linked_map",new_title)

    def show_hide_cb(self):
        if self.show_toolbar:
            self.show_toolbar = False
            self.toolbar.hide()
            self.save_button.hide()
            self.export_button.hide()
            self.zoomin_button.hide()
            self.zoomout_button.hide()
            self.image_button.hide()
            self.audio_button.hide()
            self.note_button.hide()
            self.icon_box_button.hide()
            self.help_button.hide()
            self.color_button.hide()
            self.back_button.hide()
        else:
            self.show_toolbar = True
            self.toolbar.show()
            self.save_button.show()
            self.export_button.show()
            self.zoomin_button.show()
            self.zoomout_button.show()
            self.image_button.show()
            self.audio_button.show()
            self.note_button.show()
            self.icon_box_button.show()
            self.help_button.show()
            self.color_button.show()
            self.back_button.show()

    def launch_option_cb(self,widget,option):
        if option == 'H':
            self.on_help_clicked(widget)
        elif option == 'S':
            self.export_cb(None)
        elif option == 'T':
            self.show_hide_cb()

    def title_changed_cb (self, widget, new_title):
        self.title_cp = ''
        if new_title == '':
            self.title_cp = _('Untitled Map %d' % self.map_number)
        else:
            split = new_title.splitlines ()
            if split:
                final = split.pop ()
                for s in split:
                    self.title_cp += s
                    self.title_cp += ' '
                self.title_cp += final
        if len(self.title_cp) > 27:
            x = self.title_cp[0:27]+"..."
            self.set_title (x)
        else:
            self.main_window.set_title (self.title_cp)
        self.emit ("title-changed", self.title_cp, self)

    def delete_cb (self, event):
        self.MainArea.delete_selected_elements ()

    def close_window_cb (self, event):
        self.SaveTimer.cancel = True
        self.main_window.hide ()
        self.MainArea.save_thyself ()
        del (self)

    def doc_del_cb (self, widget):
        self.emit ('window_closed', None)

    def serialize_to_xml(self, doc, top_element):
        top_element.setAttribute ("title", self.title_cp)
        top_element.setAttribute ("number", str(self.map_number))
        top_element.setAttribute ("mode", str(self.mode))
        top_element.setAttribute ("size", str((self.width,self.height)))
        top_element.setAttribute ("position", str((self.xpos,self.ypos)))
        top_element.setAttribute ("maximised", str(self.maximised))
        top_element.setAttribute ("view_type", str(self.view_type))
        top_element.setAttribute ("pane_position", str(self.pane_pos))
        top_element.setAttribute ("scale_factor", str(self.MainArea.scale_fac))
        top_element.setAttribute ("translation", str(self.MainArea.translation))
        string = doc.toxml ()
        return string.encode ("utf-8" )

    def save_map(self, filename, string):
        f = file (filename, 'w')
        f.write (string)
        f.close ()

    def doc_save_cb (self, widget, doc, top_element):
        save_string = self.serialize_to_xml(doc, top_element)
        if not self.save_file:
            sham = sha.new (save_string)
            save_loc = utils.get_save_dir ()
            self.save_file = save_loc+sham.hexdigest()+".map"
            counter = 1
            while os.path.exists(self.save_file):
            
                print "Warning: Duplicate File.  Saving to alternative"
                self.save_file = save_loc + "Dup"+str(counter)+sham.hexdigest()+".map"
                counter += 1

        self.save_map(self.save_file, save_string)
        self.emit ('file_saved', self.save_file, self)

    def on_save_clicked(self, event):
        chooser = gtk.FileChooserDialog(title=_("Save File As"), action=gtk.FILE_CHOOSER_ACTION_SAVE, \
                                        buttons=(gtk.STOCK_CANCEL, gtk.RESPONSE_CANCEL, gtk.STOCK_OPEN, gtk.RESPONSE_OK))
        chooser.set_current_name ("%s.mapz" % self.title_cp)
        response = chooser.run()
        if response == gtk.RESPONSE_OK:
            filename = chooser.get_filename ()
            self.MainArea.save_thyself ()
            tf = tarfile.open (filename, "w")
            tf.add (self.save_file, utils.strip_path_from_file_name(self.save_file))
            for t in self.MainArea.thoughts:
                if isinstance(t, ImageThought.ImageThought):
                    tf.add (t.filename, 'images/' + utils.strip_path_from_file_name(t.filename))
                    
            tf.close()

        chooser.destroy()

    def parse_file (self, filename):
        f = file (filename, 'r')
        doc = dom.parse (f)
        top_element = doc.documentElement
        self.title_cp = top_element.getAttribute ("title")
        self.map_number = int (top_element.getAttribute ("number"))
        self.mode = int (top_element.getAttribute ("mode"))
        if top_element.hasAttribute ("maximised"):
            maxi = top_element.getAttribute ("maximised")
        else:
            maxi = False
        if maxi == "True":
            self.main_window.maximize ()
        if top_element.hasAttribute ("pane_position"):
            self.pane_pos = int (top_element.getAttribute ("pane_position"))
        else:
            self.pane_pos = 500
        if top_element.hasAttribute ("view_type"):
            vt = int (top_element.getAttribute ("view_type"))
        else:
            vt = 0
        if vt == 1:
            self.extended_visible = True
        else:
            self.extended_visible = False
            
        tmp = top_element.getAttribute ("size")
        (width, height) = utils.parse_coords (tmp)
        tmp = top_element.getAttribute ("position")
        (x, y) = utils.parse_coords (tmp)
        self.main_window.resize (int (width), int (height))

        # Don't know why, but metacity seems to move the window 24 pixels
        # further down than requested.  Compensate by removing 24
        # pixels from the stored size
        y -= 24
        self.main_window.move (int (x), int (y))

        self.main_window.set_title (self.title_cp)
        self.MainArea.set_mode (self.mode)
        self.MainArea.load_thyself (top_element, doc)
        if top_element.hasAttribute("scale_factor"):
            self.MainArea.scale_fac = float (top_element.getAttribute ("scale_factor"))
        if top_element.hasAttribute("translation"):
            tmp = top_element.getAttribute("translation")
            (x,y) = utils.parse_coords(tmp)
            self.MainArea.translation = [x,y]

    def configure_cb (self, window, event):
        self.xpos = event.x
        self.ypos = event.y
        self.width = event.width
        self.height = event.height
        return False

    def window_state_cb (self, window, event):
        if event.changed_mask & gtk.gdk.WINDOW_STATE_MAXIMIZED:
            self.maximised = not self.maximised

    def toggle_range (self, arg, native_width, native_height, max_width, max_height):
        if arg.get_active ():
            self.spin_width.set_value (max_width)
            self.spin_height.set_value (max_height)
            # TODO: Fix this (and below) to cope with non-native resolutions properly
            #self.spin_width.set_sensitive (True)
            #self.spin_height.set_sensitive (True)
        else:
            #self.spin_width.set_sensitive (False)
            #self.spin_height.set_sensitive (False)
            self.spin_width.set_value (native_width)
            self.spin_height.set_value (native_height)

    def export_cb (self, event):
        maxx, maxy = self.MainArea.get_max_area ()

        x, y, width, height, bitdepth = self.MainArea.window.get_geometry ()
        #glade = gtk.glade.XML (utils.get_data_file_name('chartr_browser.glade'))
        try:
            glade = gtk.glade.XML (utils.get_data_file_name('./ui/chartr_browser.glade'))
        except:
            glade = gtk.glade.XML (utils.get_data_file_name('../data/chartr_browser.glade'))
        dialog = glade.get_widget ('ExportImageDialog')
        box = glade.get_widget ('dialog_insertion')
        fc = gtk.FileChooserWidget(gtk.FILE_CHOOSER_ACTION_SAVE)
        box.pack_end (fc)

        filter_mapping = [  (_('All Files'), ['*']),
                            (_('PNG Image (*.png)'), ['*.png']),
                            (_('JPEG Image (*.jpg, *.jpeg)'), ['*.jpeg', '*.jpg']),
                            (_('SVG Vector Image (*.svg)'), ['*.svg']),
                            (_('PDF Portable Document (*.pdf)'), ['*.pdf']) ]

        for (filter_name, filter_patterns) in filter_mapping:
            fil = gtk.FileFilter ()
            fil.set_name(filter_name)
            for pattern in filter_patterns:
                fil.add_pattern(pattern)
            fc.add_filter(fil)

        fc.set_current_name ("%s.png" % self.title_cp)
        rad = glade.get_widget ('rb_complete_map')
        rad2 = glade.get_widget ('rb_visible_area')
        self.spin_width = glade.get_widget ('width_spin')
        self.spin_height = glade.get_widget ('height_spin')
        self.spin_width.set_value (maxx)
        self.spin_height.set_value (maxy)
        self.spin_width.set_sensitive (False)
        self.spin_height.set_sensitive (False)

        rad.connect ('toggled', self.toggle_range, width, height,maxx,maxy)

        fc.show ()
        while 1:
        # Cheesy loop.  Break out as needed.
            response = dialog.run()
            if response == gtk.RESPONSE_OK:
                ext_mime_mapping = { 'png':'png', 'jpg':'jpeg', 'jpeg':'jpeg', \
                                     'svg':'svg', 'pdf':'pdf' ,'ps':'ps'}
                filename = fc.get_filename()
                ext = filename[filename.rfind('.')+1:]

                try:
                    mime = ext_mime_mapping[ext]
                    break
                except KeyError:
                    msg = gtk.MessageDialog(self, gtk.DIALOG_DESTROY_WITH_PARENT, gtk.MESSAGE_ERROR, gtk.BUTTONS_OK, \
                                            _("Unknown file format"))
                    msg.format_secondary_text (_("The file type '%s' is unsupported.  Please use the suffix '.png',"\
                                               " '.jpg' or '.svg'." % ext))
                    msg.run ()
                    msg.destroy ()
            else:
                dialog.destroy ()
                return
                
        true_width = int (self.spin_width.get_value ())
        true_height = int (self.spin_height.get_value ())
        native = not rad.get_active ()
        dialog.destroy ()

        if mime in ['png', 'jpg']:
            self.save_as_pixmap(filename, mime, true_width, true_height, bitdepth, native)
        else:
            surface = None
            if mime == 'svg': 
                surface = cairo.SVGSurface(filename, true_width, true_height)
            elif mime == 'pdf':
                surface = cairo.PDFSurface(filename, true_width, true_height)
            elif mime == 'ps':
                surface = cairo.PSSurface(filename,true_width,true_height)

            self.save_surface(surface, true_width, true_height, native)

    def save_as_pixmap(self, filename, mime, width, height, bitdepth, native):
        pixmap = gtk.gdk.Pixmap (None, width, height, bitdepth)
        self.MainArea.export (pixmap.cairo_create (), width, height, native)

        pb = gtk.gdk.Pixbuf.get_from_drawable(gtk.gdk.Pixbuf(gtk.gdk.COLORSPACE_RGB, True, 8, width, height), \
                                              pixmap, \
                                              gtk.gdk.colormap_get_system(), \
                                              0, 0, 0, 0, width, height)
        pb.save(filename, mime)
        
    def save_surface(self, surface, width, height, native):
        cairo_context = cairo.Context(surface)
        context = pangocairo.CairoContext(cairo_context)
        self.MainArea.export(context, width, height, native)
        surface.finish()

    def selection_changed_cb (self, area, start, end, text):
        clip = gtk.Clipboard (selection="PRIMARY")
        if text:
            clip.set_text (text)
        else:
            clip.clear ()

    def edit_activated_cb (self, menu):
            # FIXME: Keybindings should also be deactivated.
            self.cut.set_sensitive (False)
            self.copy.set_sensitive (False)
            self.paste.set_sensitive (False)
            self.link.set_sensitive (False)
            if self.extended.is_focus ():
                self.paste.set_sensitive (True)
                stend = self.extended.get_buffer().get_selection_bounds()
                if len (stend) > 1:
                    start,end = stend
                else:
                    start = end = stend
            else:
                start, end = self.MainArea.get_selection_bounds ()
                try:
                    if self.mode == MMapArea.MODE_EDITING and len(self.MainArea.selected) and \
                       self.MainArea.selected[0].editing:
                        self.paste.set_sensitive (True)
                except AttributeError:
                    pass
                if len (self.MainArea.selected) == 2:
                    self.link.set_sensitive (True)

            if start and start != end:
                self.cut.set_sensitive (True)
                self.copy.set_sensitive (True)

    def cut_text_cb (self, event):
        clip = gtk.Clipboard ()
        if self.extended.is_focus ():
            self.extended.get_buffer().cut_clipboard (clip)
        else:
            self.MainArea.cut_clipboard (clip)

    def copy_text_cb (self, event):
        clip = gtk.Clipboard ()
        if self.extended.is_focus ():
            self.extended.get_buffer().copy_clipboard (clip)
        else:
            self.MainArea.copy_clipboard (clip)

    def paste_text_cb (self, event):
        clip = gtk.Clipboard ()
        if self.extended.is_focus ():
            self.extended.get_buffer().paste_clipboard (clip)
        else:
            self.MainArea.paste_clipboard (clip)

    def start_timer (self):
        self.SaveTimer = PeriodicSaveThread.PeriodicSaveThread(self.MainArea)
        self.SaveTimer.setDaemon( True)
        self.SaveTimer.start()

